<template>
  <a-card :bordered='false'>
    <div class='crd-material-tabs'>
      <a-tabs type='card' :activeKey='queryParam.materialType' size='large' @change='tabChange' class='tabPage'>
        <a-tab-pane :key='1' tab='图片'>
        </a-tab-pane>
        <a-tab-pane :key='2' tab='视频'>
        </a-tab-pane>
        <a-tab-pane :key='3' tab='音频'>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 查询区域 -->
    <div class='table-page-search-wrapper search-box-cuesList'>
      <a-form layout='inline'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='10' :md='8' :sm='24'>
            <a-form-item>
              <a-input placeholder='请输入标签名称' v-model='queryParam.keyword'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='10' :md='8' :sm='24'>
            <a-form-item>
              <a-tree-select
                v-model="queryParam.groupId"
                :tree-data="treeData"
                :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
                allow-clear></a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='display: flex;align-items: center;'>
            <a-button type='primary' @click='searchQuery' icon='search' title='搜索' style="margin-right: 5px"></a-button>
            <a-button @click='materialModal = true' type='primary' icon='plus'>上传素材</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <!-- table区域-begin -->
    <div class='crd-material-content' style='background:#fff !important;margin-top:20px;padding:20px'>
      <div v-show='materialType == 1'>
        <div class='crd-material-content-title'>
          <div class='title'>图片（共{{ ipagination.total }}条）</div>
          <div>
          </div>
        </div>
        <div class='crd-material-content-group'>
          <div class='crd-material-content-group-list'>
<!--            <div v-for='(item,index) of groupList' :class='{selected:item.groupId == queryParam.groupId}' :key='index'-->
<!--                 @click='groupChange(item)'>-->
<!--              {{ item.groupName }}（{{ item.cnt }}）-->
<!--            </div>-->
          </div>
          <div class='crd-material-content-group-add'>
<!--            <div v-has="'materia:add'" style='margin-right: 20px;display: flex;float: left;cursor: pointer'-->
<!--                 @click='groupModal = true'>-->
<!--              <a-icon type='plus-circle' style='margin-right: 3px;' />-->
<!--              <span style='line-height: 18px;'>新建分组</span>-->
<!--            </div>-->
            <div v-has="'materia:select'" style='display: flex;float: left;cursor: pointer;align-items: center'
                 @click='handleFileClassify'>
              <a-icon type='setting' style='margin-right: 3px;' />
              <span style='line-height: 18px;'>管理分组</span>
            </div>
          </div>
        </div>
        <div class='crd-material-content-list'>
          <div class='crd-material-content-list-item' v-for='(item,index) of dataSource' :key='index'>
            <div class='crd-material-content-list-item-box'>
              <img :src='item.materialUrl' :preview='item.materialUrl' />
              <div class='icons'>
                <div>
                  <a-icon type='edit' theme='outlined' @click='editName(item,index)' />
                </div>
                <div>
                  <a-popconfirm title='确定删除吗?' @confirm='() => matDelete(item)'>
                    <a-icon type='delete' theme='outlined' />
                  </a-popconfirm>
                </div>
                <div>
                  <a-icon type='download' theme='outlined' @click='downLoadImg(item,index)' />
                </div>
              </div>
            </div>
            <div class='crd-material-content-list-item-name'>{{ item.keyword.replace(',', '') }}</div>
          </div>
        </div>
        <div style='width: 100%; display: flex; justify-content: center;'>
          <a-pagination size='small' v-model='queryParam.pageNo' :total='ipagination.total' @change='pageChange' />
        </div>
      </div>
      <div v-show='materialType == 2' class='crd-material-content-table'>
        <div class='crd-material-content-title'>
          <div class='title'>视频（共{{ ipagination.total }}条）</div>
          <div>
          </div>
        </div>
        <div class='crd-material-content-group'>
          <div class='crd-material-content-group-list'>
<!--            <div v-for='(item,index) of groupList' :class='{selected:item.groupId == queryParam.groupId}' :key='index'-->
<!--                 @click='groupChange(item)'>-->
<!--              {{ item.groupName }}（{{ item.cnt }}）-->
<!--            </div>-->
          </div>
          <div class='crd-material-content-group-add'>
<!--            <div v-has="'materia:add'" style='margin-right: 20px;display: flex;float: left;cursor: pointer'-->
<!--                 @click='groupModal = true'>-->
<!--              <a-icon type='plus-circle' style='margin-right: 3px;' />-->
<!--              <span style='line-height: 18px;'>新建分组</span>-->
<!--            </div>-->
            <div v-has="'materia:select'" style='display: flex;float: left;cursor: pointer;align-items: center'
                 @click='handleFileClassify'>
              <a-icon type='setting' style='margin-right: 3px;' />
              <span style='line-height: 18px;'>管理分组</span>
            </div>
          </div>
        </div>
        <a-table ref='table' size='middle' rowKey='id' :columns='columns' :dataSource='dataSource'
                 :pagination='ipagination'
                 :loading='loading' :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
                 @change='handleTableChange'>
          <img v-if="record.materialCoverUrl" style='width:50px;height:50px;cursor: pointer' slot='pic' slot-scope='text, record' :src='record.materialCoverUrl'
               @click='preview(record.materialUrl)'  alt=""/>
          <div v-else class='voicePlay' slot='pic' slot-scope='text, record' @click='preview(record.materialUrl)' title='播放'>
            <a-icon type='play-circle' />
          </div>
          <span slot='action' slot-scope='text, record'>
            <!-- <a @click="handleEdit(record)">编辑</a> -->
            <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
              <a title='删除'>
                <a-icon type='delete' theme='filled' style='color:#ed7770' /></a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <div v-show='materialType == 3' class='crd-material-content-table'>
        <div class='crd-material-content-title'>
          <div class='title'>音频（共{{ ipagination.total }}条）</div>
          <div>
          </div>
        </div>
        <div class='crd-material-content-group'>
          <div class='crd-material-content-group-list'>
<!--            <div v-for='(item,index) of groupList' :class='{selected:item.groupId == queryParam.groupId}' :key='index'-->
<!--                 @click='groupChange(item)'>-->
<!--              {{ item.groupName }}（{{ item.cnt }}）-->
<!--            </div>-->
          </div>
          <div class='crd-material-content-group-add'>
<!--            <div v-has="'materia:add'" style='margin-right: 20px;display: flex;float: left;cursor: pointer'-->
<!--                 @click='groupModal = true'>-->
<!--              <a-icon type='plus-circle' style='margin-right: 3px;' />-->
<!--              <span style='line-height: 18px;'>新建分组</span>-->
<!--            </div>-->
            <div v-has="'materia:select'" style='display: flex;float: left;cursor: pointer;align-items: center'
                 @click='handleFileClassify'>
              <a-icon type='setting' style='margin-right: 3px;' />
              <span style='line-height: 18px;'>管理分组</span>
            </div>
          </div>
        </div>
        <a-table ref='table' size='middle' rowKey='id' :columns='columns' :dataSource='dataSource'
                 :pagination='ipagination'
                 :loading='loading' :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
                 @change='handleTableChange'>
          <div class='voicePlay' slot='pic' slot-scope='text, record' @click='preview(record.materialUrl)' title='播放'>
            <a-icon type='play-circle' />
          </div>
          <span slot='action' slot-scope='text, record'>
            <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
              <a title='删除'>
                <a-icon type='delete' theme='filled' style='color:#ed7770' /></a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <a-pagination v-show='queryParam.pages' show-quick-jumper :default-current='queryParam.current'
                    :total='queryParam.pages'
                    @change='onChange' />
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <crdMaterialInfo-modal ref='modalForm' @ok='modalFormOk'></crdMaterialInfo-modal>
    <!-- 新增分组 -->
    <a-modal v-model='groupModal' title='新增分组' @ok='groupConfirm' cancelText='关闭' class='pop-table'
             :closable='false'>
      <a-form style='margin:30px 0'>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='分组名称'>
          <a-input placeholder='输入分组名称' v-model='groupName' />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model='groupSelectModal' :width='700' title='管理分组' :footer='null' class='pop-table'
             :closable='false'>
      <div class='group_ul'>
        <div class='group_li' v-for='item in groupList'>
          <div class='group_name' v-if="item.isEdit != '1'">{{ item.groupName }}</div>
          <div class='group_inp' v-if="item.isEdit == '1'">
            <a-input v-model='item.groupName' :value='item.groupName'></a-input>
            <a-icon type='check' style='margin-right: 10px;' @click='editGroup(item.groupId,item.groupName)' />
            <a-icon type='close' style='color: red' @click='removeGroupEdit(item)' />
          </div>
          <div class='group_opt'>
            <a @click='groupEditFn(item)' title='编辑'>
              <a-icon type='edit' theme='filled' />
            </a>
            <a-divider type='vertical' style='margin-top: 10px;' />
            <a-popconfirm title='删除分组，同时删除分组内容所有图片' @confirm='() => deleteGroup(item.groupId)'>
              <a title='删除'>
                <a-icon type='delete' theme='filled' style='color:#ed7770' />
              </a>
            </a-popconfirm>

          </div>
        </div>
      </div>
      <div style='height: 60px;line-height: 60px;text-align: right;padding-right: 20px;'>

        <a-button @click='groupSelectConfirm'>关闭</a-button>
      </div>
    </a-modal>

    <!-- 新增素材 -->
    <a-modal v-model='materialModal' title='新增素材' @ok='materialConfirm' cancelText='关闭' class='pop-table'
             @cancel='materialCancel' :closable='false' :body-style="{maxHeight: '900px', overflow: 'auto'}">
      <a-form style='margin:30px 0'>
        <a-form-item v-show='queryParam.materialType == 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='图片上传'>
          <j-image-upload accept='image/*' ref='imageUp' v-model='requestParam.materialUrl' @change='imgChange'
                          @beforeUpload='beforeUpload' :beforeflag='true' :is-multiple='true'></j-image-upload>
          <div style="margin-top: -20px; color: #1890FF" v-if="requestParam.materialUrl">
            <span @click="copperUpload" style="cursor: pointer">裁剪图片</span>
            <span @click="imageAdjustVisible = true" style="margin-left: 10px; cursor: pointer">调整图片</span>
          </div>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 2' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='视频上传'>
          <j-upload accept='video/*' v-model='requestParam.materialUrl' @change='fileChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 3' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='音频上传'>
          <j-upload accept='audio/*' v-model='requestParam.materialUrl' @change='fileChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 2' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='输入素材封面'>
          <j-upload ref='imageUp' v-model='requestParam.materialCoverUrl' @change='coverChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='图片标题'>
          <a-input placeholder='输入图片标题' v-model='requestParam.materialName' />
        </a-form-item>
        <a-form-item v-show='queryParam.materialType != 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='输入素材标题'>
          <a-input placeholder='输入素材标题' v-model='requestParam.remark' />
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='输入标签'>
          <a-input placeholder='输入标签' v-model='requestParam.keyword' />
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属分组'>
<!--          <a-select v-model='requestParam.groupId' placeholder='请选择标签' :default-value='1' class='select-box'>-->
<!--            <a-select-option v-for='(item,index) of groupList' :key='index' :value='item.groupId'>{{ item.groupName }}-->
<!--            </a-select-option>-->
<!--          </a-select>-->
          <a-tree-select
            v-model="requestParam.groupId"
            :tree-data="treeData"
            :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
            allow-clear></a-tree-select>
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='选择权限'>
          <a-tree-select
            v-model='requestParam.depart'
            :tree-data='departTreeData'
            tree-checkable
            search-placeholder='选择权限'
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model='materialNameModal' title='修改素材' @ok='materialNameConfirm' cancelText='关闭' class='pop-table'
             :closable='false'>
      <a-form style='margin:30px 0'>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='输入名称'>
          <a-input placeholder='输入名称' v-model='materialName' />
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='修改分组'>
          <a-select v-model='changeChange.groupId' placeholder='请选择标签' :default-value='1' class='select-box'>
            <a-select-option v-for='(item,index) of groupList' :key='index' :value='item.groupId'>{{ item.groupName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 视频预览 -->
    <a-modal title='视频预览' :visible='previewVisible' :footer='null' @cancel='previewVisible = false'
             class='pop-table'
             :closable='false'>
      <video controls v-if='previewVisible' style='margin:0;transform: translate(0, 0);width:100%'>
        <source :src='materialUrl' type='video/webm'>
      </video>
    </a-modal>
    <!-- 音频预览 -->
    <a-modal title='音频预览' :visible='previewVisible2' :footer='null' @cancel='previewVisible2 = false'
             class='pop-table'
             :closable='false'>
      <audio controls='controls' :src='materialUrl' v-if='previewVisible2'
             style='margin:30px 0;transform: translate(0, 0);width:100%'></audio>
    </a-modal>
    <!--  -->
    <a-modal :visible='cropperVisible' title='裁剪图片' :maskClosable='false' :confirmLoading='confirmLoading'
             :width='600'
             @cancel='cropperVisible = false'>
      <a-row>
        <a-col :xs='24' :md='24' :style="{height: '400px'}">
          <vue-cropper ref='cropper' :img='options.img' :info='true' :autoCrop='options.autoCrop'
                       :autoCropWidth='options.autoCropWidth'
                       :autoCropHeight='options.autoCropHeight' :fixedBox='options.fixedBox' @realTime='realTime'>
          </vue-cropper>
        </a-col>
        <a-col :xs="24" :md="24" style="margin-top: 16px; text-align: center;">
          <a-button type='primary'  @click="setCropSize(640, 480)" style="margin-right: 10px;">640×480比例</a-button>
          <a-button type='primary'  @click="setCropSize(1920, 1080)">1920×1080比例</a-button>
        </a-col>
      </a-row>
      <template slot='footer'>
        <a-button key='back' @click='cancelHandel'>取消</a-button>
        <a-button key='submit' type='primary' :loading='confirmLoading' @click='okHandel'>确定</a-button>
      </template>
    </a-modal>
    <a-modal
      :visible="imageAdjustVisible"
      title="图像调整"
      :footer="null"
      :maskClosable="false"
      :width="600"
      @cancel="imageAdjustVisible = false"
      :destroyOnClose="true"
    >
      <image-adjust :nowImg="requestParam.materialUrl" @updateImg="updateImageAdjust" />
    </a-modal>
    <file-classify-modal ref="fileClassifyModal" @refresh="queryFileClassify"></file-classify-modal>
  </a-card>
</template>

<script>
import ImageAdjust from './ImageAdjust' // 引入新组件
import { queryDepartTreeList } from '@/api/api'
import {
  getAction,
  httpAction,
  deleteAction,
  postAction
} from '@/api/manage'
import CrdMaterialInfoModal from './modules/CrdMaterialInfoModal'
import {
  JeecgListMixin
} from '@/mixins/JeecgListMixin'
import {
  VueCropper
} from 'vue-cropper'
import axios from 'axios'
import FileClassifyModal from '@views/disk/modules/FileClassifyModal.vue'

export default {
  name: 'CrdMaterialInfoList',
  mixins: [JeecgListMixin],
  components: {
    FileClassifyModal,
    ImageAdjust,
    CrdMaterialInfoModal,
    VueCropper
  },
  data() {
    return {
      description: '素材信息管理页面',
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      departTreeData: [],
      // 表头
      columns: [{
        title: '#',
        dataIndex: '',
        key: 'rowIndex',
        width: 60,
        align: 'center',
        customRender: function(t, r, index) {
          return parseInt(index) + 1
        }
      },
        {
          title: '名称',
          align: 'center',
          dataIndex: 'remark'
        },
        {
          title: '标签',
          align: 'center',
          dataIndex: 'keyword'
        },
        {
          title: '素材内容',
          align: 'center',
          dataIndex: 'materialCoverUrl',
          scopedSlots: {
            customRender: 'pic'
          }
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      // dataSource: [],
      url: {
        list: '/materia/crdMaterialInfo/list',
        delete: '/materia/crdMaterialInfo/delete'
      },
      tagList: [],
      materialType: 1,
      groupList: [],
      groupModal: false,
      groupName: '',
      requestParam: {
        materialType: 1,
        groupId: '',
        materialName: '',
        materialUrl: '',
        materialCoverUrl: '',
        remark: '',
        depart: [],
        keyword: ''
      },
      materialModal: false,
      queryParam: {
        materialType: 1,
        groupId: '',
        pageNo: 1,
        pageSize: 999
      },
      materialUrl: '',
      previewVisible: false,
      previewVisible2: false,
      options: {
        img: '',
        autoCrop: true,
        autoCropWidth: 200,
        autoCropHeight: 200,
        fixedBox: false
      },
      cropperVisible: false,
      confirmLoading: false,
      previews: {},
      resolve: '',
      test: '',
      userList: [],
      userSelected: '',
      imageTotal: 0,
      materialNameModal: false,
      groupSelectModal: false,
      materialName: '',
      changeChange: {},
      editMaterial: {},
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      imageAdjustVisible: false,
      treeData: [],
    }
  },
  mounted() {
    this.queryFileClassify();
    this.getGroupList()
    getAction('/materia/crdMaterialInfo/getKeywords').then(res => {
      this.userList = res.result
    })
    this.ipagination.pageSize = 12
    this.loadData()
    this.loadTree()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  watch: {
    dataSource(newValue, oldValue) {
      console.log(this.ipagination)
      this.materialType = this.queryParam.materialType
    }
  },
  methods: {
    //文件分类管理
    handleFileClassify() {
      this.$refs.fileClassifyModal.show();
    },
    async queryFileClassify() {
      const params = {fileGroupType: 0};
      const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
      if (res && res.success) {
        this.treeData  = res.result;
      }
    },
    loadTree() {
      this.departTreeData = []
      queryDepartTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            this.departTreeData.push(temp)
          }
        }
      })
    },
    materialNameConfirm() {
      let groupNames = this.groupList.filter(item => item.groupId === this.changeChange.groupId)
      postAction('/materia/crdMaterialInfo/editName', {
        id: this.editMaterial.id,
        materialName: this.materialName,
        groupId: this.changeChange.groupId,
        groupName: (groupNames && groupNames.length > 0) ? groupNames[0].groupName : ''
      }).then(res => {
        this.materialNameModal = false
        this.$message.success('修改成功')
        this.loadData()
        this.getGroupList()
      })
    },
    editName(item) {
      console.log(item)
      this.materialNameModal = true
      this.materialName = item.materialName
      this.editMaterial = item
    },
    downLoadImg(item) {
      window.open(item.materialUrl)
    },
    pageChange(a, b) {
      this.queryParam.pageNo = a
      this.ipagination.current = a
      console.log(this.queryParam)
      this.loadData()
    },
    handleSearch(value) {
      getAction('/materia/crdMaterialInfo/getKeywords', {
        keyword: value
      }).then(res => {
        this.userList = res.result
      })
    },
    handleChange(value) {
      this.userSelected = value
      this.queryParam.keyword = this.userList[value]
    },
    cropper() {

    },
    copperUpload() {
      console.log(this.requestParam.materialUrl)
      this.options.img = this.requestParam.materialUrl
      this.cropperVisible = true
    },
    beforeUpload(file, resolve) {
      console.log(file)
      this.options.img = window.URL.createObjectURL(file)
      this.cropperVisible = true
      this.resolve = resolve
    },
    cancelHandel() {
      this.cropperVisible = false
      this.resolve()

    },
    okHandel() {
      // this.cropperVisible = false
      this.$refs.cropper.getCropData((data) => {
        let file = this.dataURLToFile(data, '默认')
        console.log(file)
        this.updateImg(file)
      })
    },
    updateImg(file) {
      let formData = new FormData()
      let fileOfBlob = new File([file], '.jpg') // 命名图片名
      formData.append('file', fileOfBlob)
      axios({
        url: this.uploadAction,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;charset=UTF-8'
        },
        data: formData
      }).then(res => {
        console.log(res,'1111')
        if (res.data.success && res.data.code === 0) {
          this.requestParam.materialUrl = res.data.message
          this.$message.success('修改成功')
          this.materialNameModal = false
          // if (this.watermark) {
          //   this.watermark = false
          // }
          if (this.cropperVisible) {
            this.cropperVisible = false
          }
        }
      })
    },
    // 添加更新图像的方法
    updateImageAdjust(file) {
      let formData = new FormData();
      let fileOfBlob = new File([file], '.jpg'); // 命名图片名
      formData.append('file', fileOfBlob);

      axios({
        url: this.uploadAction,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;charset=UTF-8'
        },
        data: formData
      }).then(res => {
        if (res.data.success && res.data.code === 0) {
          this.requestParam.materialUrl = res.data.message;
          this.$message.success('图片调整成功');
          this.imageAdjustVisible = false;
        }
      });
    },
    realTime(data) {
      this.previews = data
    },
    getGroupList() {
      //分组信息
      getAction('materia/crdMaterialInfo/queryGroupInfo', {
        materialType: this.queryParam.materialType
      }).then(res => {
        this.groupList = res.result
      })
    },
    groupEditFn(record) {
      this.groupList.forEach(item => {
        if (item.groupId == record.groupId) {
          item.isEdit = 1
        } else {
          item.isEdit = 0
        }
      })

      var groupList = JSON.parse(JSON.stringify(this.groupList))
      this.groupList = []
      this.groupList = JSON.parse(JSON.stringify(groupList))
      console.log(this.groupList)
    },
    removeGroupEdit(record) {
      this.groupList.forEach(item => {
        if (item.groupId == record.groupId) {
          item.isEdit = 0
        } else {
          item.isEdit = 0
        }
      })

      var groupList = JSON.parse(JSON.stringify(this.groupList))
      this.groupList = []
      this.groupList = JSON.parse(JSON.stringify(groupList))
      console.log(this.groupList)
    },
    editGroup(id, groupName) {
      httpAction('materia/crdMaterialGroup/edit', {
        id: id,
        groupName: groupName
      }, 'put').then(res => {
        if (res.code == '200') {
          var record = {
            groupId: id
          }
          this.removeGroupEdit(record)
        }
      })
    },
    deleteGroup(id) {
      console.log('删除分组')
      httpAction('materia/crdMaterialGroup/delete?id=' + id, {}, 'get').then(res => {
        if (res.code == '200') {

          this.getGroupList()
        }
      })
    },
    groupConfirm() {
      if (this.groupName == null || this.groupName == '') {
        this.$message.warning('请输入分组名称！')
      } else {
        httpAction('materia/crdMaterialGroup/add', {
          groupName: this.groupName
        }, 'post').then(res => {
          this.groupModal = false
          this.getGroupList()
        })
      }

    },
    getList() {
      //素材列表
      getAction('materia/crdMaterialInfo/list', this.queryParam).then(res => {
        this.dataSource = res.result.records
        this.ipagination.total = res.result.total
      })
    },
    onChange(pageNumber) {
      console.log('Page: ', pageNumber)
    },
    matDelete(item) {
      deleteAction('materia/crdMaterialInfo/delete', {
        id: item.id
      }, 'delete').then(res => {
        if (res.success) {
          this.getList()
          this.getGroupList()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    groupSelectConfirm() {
      this.groupSelectModal = false
    },
    imgChange(path, item) {
      this.requestParam.materialUrl = path
      this.requestParam.materialList = item.fileList
      this.requestParam.materialName = ''
      item.fileList.forEach(file => {
        this.requestParam.materialName += file.name + ', '
      })
    },
    fileChange(item) {
      this.requestParam.materialUrl = item.file.response.result.url
    },
    coverChange(path, item) {
      this.requestParam.materialCoverUrl = item.file.response.result.url
    },
    materialCancel() {
      this.requestParam = {
        materialType: this.queryParam.materialType,
        groupId: '',
        materialName: '',
        materialUrl: '',
        materialCoverUrl: '',
        remark: '',
        keyword: ''
      }
    },
    materialConfirm() {
      console.log(this.requestParam.depart)
      this.requestParam.materialType = this.queryParam.materialType
      // this.requestParam.groupId = this.queryParam.groupId;
      // if (!this.requestParam.keyword) {
      //   this.$message.warning('请输入标签')
      //   return false
      // }
      if (!this.requestParam.materialUrl) {
        this.$message.warning('请上传素材')
        return false
      }
      if (!this.requestParam.keyword) {
        this.$message.warning('请输入标签')
        return false
      }
      if (!this.requestParam.groupId) {
        this.$message.warning('请选择有效分组')
        return false
      }
      if (!this.requestParam.depart || this.requestParam.depart.length === 0) {
        this.$message.warning('请选择权限')
        return false
      }
      if (this.requestParam.materialList && this.requestParam.materialList.length > 0) {
        let httpList = []
        this.requestParam.materialList.forEach(material => {
          let param = { ...this.requestParam }
          param.materialName = material.name
          param.materialUrl = material.url
          delete param.materialList
          httpList.push(httpAction('materia/crdMaterialInfo/add', param, 'post'))
        })
        Promise.all(httpList).then(res => {
          this.addMaterialSuccess()
        })
      } else {
        httpAction('materia/crdMaterialInfo/add', this.requestParam, 'post').then(res => {
          this.addMaterialSuccess()
        })
      }
    },
    addMaterialSuccess() {
      this.materialModal = false
      this.getList()
      this.loadData()
      this.requestParam = {
        materialType: this.queryParam.materialType,
        groupId: '',
        materialName: '',
        materialUrl: '',
        materialCoverUrl: '',
        remark: '',
        depart: this.requestParam.depart,
        keyword: ''
      }
      this.getGroupList()
    },
    preview(materialUrl) {
      this.materialUrl = materialUrl
      this.queryParam.materialType == 2 ? this.previewVisible = true : this.previewVisible2 = true
    },
    tabChange(key) {
      this.queryParam.materialType = key
      this.getGroupList()
      this.loadData()
    },
    groupChange(item) {
      this.queryParam.groupId = item.groupId
      this.loadData()
      this.$forceUpdate()
    },
    dataURLToFile(dataURL, filename) {

      const arr = dataURL.split(','),
        mime = arr[0].match(/:(.*?);/)[1], //mime类型 image/png
        bstr = atob(arr[1]) //base64 解码

      let n = bstr.length,
        u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }

      return new File([u8arr], filename, { type: mime })
      //return new Blob([a8arr], {type: mime});
    },
    setCropSize(width, height) {
      // 获取弹窗和图片的实际尺寸
      const modalWidth = 560; // 弹窗内容区宽度(减去padding)
      const modalHeight = 400; // 图片显示区域高度

      // 计算最大可显示尺寸(留20px边距)
      const maxWidth = modalWidth - 20;
      const maxHeight = modalHeight - 20;

      // 计算宽高比例
      const ratio = width / height;

      // 根据弹窗尺寸限制裁剪框最大尺寸
      let finalWidth, finalHeight;
      if (width > maxWidth) {
        finalWidth = maxWidth;
        finalHeight = finalWidth / ratio;
      } else if (height > maxHeight) {
        finalHeight = maxHeight;
        finalWidth = finalHeight * ratio;
      } else {
        finalWidth = width;
        finalHeight = height;
      }

      // 更新裁剪框尺寸
      this.options.autoCropWidth = Math.floor(finalWidth);
      this.options.autoCropHeight = Math.floor(finalHeight);

      // 强制刷新组件
      this.$refs.cropper.refresh();
    },
  }
}
</script>
<style lang='less' scoped>
@import '~@assets/less/common.less';

.crd-material {

  &-content {

    &-title {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;

      .title {
        font-weight: bold;
        font-size: 20px;
      }
    }

    &-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      &-list {
        width: 100%;
        flex: 1;
        display: flex;
        flex-wrap: wrap;

        & > div {
          padding: 6px 16px;
          border-radius: 5px;
          margin-right: 10px;
          cursor: pointer;
        }

        .selected {
          color: #1890ff;
          border: 1px solid #1890ff;
        }
      }

      &-add {
        max-width: 200px;
      }
    }

    &-list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding: 0 30px;
      box-sizing: border-box;

      &-item {
        margin: 0 40px 10px 0;

        &-box {
          width: 15vw;
          height: 15vw;
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #000;

          .icons {
            width: 100%;
            position: absolute;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.5);
            display: flex;
            align-items: center;
            padding: 4px 0;

            & > div {
              width: 50%;
              text-align: center;
              cursor: pointer;

              &:first-child {
                border-right: 1px solid #fff
              }
              &:last-child {
                border-left: 1px solid #fff
              }
            }
          }
        }

        &-name {
          text-align: center;
          width: 15vw;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        img {
          max-height: 100%;
          max-width: 100%;
        }
      }
    }
  }
}

video {
  max-width: 1000px;
  max-height: 600px;
  transform: translate(-50%, 0);
  margin-left: 50%;
}

.voicePlay {
  color: #40a9ff;
  text-decoration: underline;
  cursor: pointer;
}

.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 180px;
  height: 180px;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
  }
}

.group_ul {
  padding: 10px;
}

.group_ul .group_li {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: flex;
}

.group_ul .group_li .group_name {
  width: 400px;
}

.group_ul .group_li .group_inp {
  width: 280px;
}

.group_ul .group_li .group_inp input {
  width: 200px;
  margin-right: 20px;
}

.group_ul .group_li .group_inp i {
  color: green;
}

.group_ul .group_li .group_opt {
  margin-left: auto;
  width: 80px;
  display: flex;
}
</style>
